var generateMatrix = function (n) {
  let top = 0, bottom = n - 1, left = 0, right = n - 1, num = 1;
  const res = new Array(n);
  for (let i = 0; i < n; i++) {
    res[i] = new Array(n);
  }
  while (num <= n * n) {
    for (let i = left; i <= right; i++) {
      res[top][i] = num, num++;
    }
    top++
    for (let i = top; i <= bottom; i++) {
      res[i][right] = num; num++;
    }
    right--
    for (let i = right; i >= left; i--) {
      res[bottom][i] = num; num++;
    }
    bottom--
    for (let i = bottom; i >= top; i--) {
      res[i][left] = num; num++;
    }
    left++
  }
  return res
};

generateMatrix(3)